package org.krishna.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.krishna.Dao.SaveData;
import org.krishna.File.ExcelData;
import org.krishna.jaxb.xml.Course;
import org.krishna.jaxb.xml.ObjectFactory;
import org.krishna.jaxb.xml.Parent;
import org.krishna.jaxb.xml.Parents;
import org.krishna.jaxb.xml.Student;
import org.krishna.mail.SendMail;
import org.krishna.model.Login;
import org.krishna.xml.GenerateXml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

//@Service("dataTransferHandler")
@Service("serviceHandler")
@Transactional(propagation = Propagation.REQUIRED)
public class ServiceHandlerImpl implements ServiceHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(ServiceHandlerImpl.class);

	@Autowired
	@Qualifier("saveData")
	SaveData saveData;
	
	 @Autowired
	 @Qualifier("sendMail")
	 private SendMail sendMail;

	@Override
	public boolean registerUser(String userName, String password, String type) {
		Login login = new Login(userName, password, type);
		saveData.registerUser(login);
		return false;
	}

	@Override
	public void prepareReport() throws Exception {
		OutputStream outputStream = null;
		outputStream = new FileOutputStream("E:\\ab\\my.xml");
		Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream));
		writer.write(GenerateXml.XML_START_TAG + "\n");
		writer.write(GenerateXml.PARENTS_START_XML_TAG + "\n");
		Parents parents = new ObjectFactory().createParents();
		GenerateXml generateXml = new GenerateXml();
		generateXml.buildParents(parents,saveData);
		writer.write(GenerateXml.PARENTS_END_XML_TAG);
		
		try {

			// create JAXB context and initializing Marshaller
			JAXBContext jaxbContext = JAXBContext.newInstance(Parents.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

			// for getting nice formatted output
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			//specify the location and name of xml file to be created
			File XMLfile = new File("E:\\ab\\my.xml");
			
			// Writing to XML file
			jaxbMarshaller.marshal(parents, XMLfile); 
			// Writing to console
			jaxbMarshaller.marshal(parents, System.out); 
		
		} catch (JAXBException e) {
			// some exception occured
			e.printStackTrace();
		}
		
		Parents parentsObject = this.getObjectFromFile();
		System.out.println("Parents Details are :"+parentsObject);
		this.generateReport(parentsObject);
		
		
	}
	
	private Parents getObjectFromFile(){
		Parents parents = null;
		try {
			
			// create JAXB context and initializing Marshaller
			JAXBContext jaxbContext = JAXBContext.newInstance(Parents.class);

			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			
			// specify the location and name of xml file to be read
			File XMLfile = new File("E:\\ab\\my.xml");
			
			// this will create Java object - Parents from the XML file
			parents = (Parents) jaxbUnmarshaller.unmarshal(XMLfile);
		  }catch (JAXBException e) {
				// some exception occured
				e.printStackTrace();
		  }
		
		return parents;
	}
	
	private void generateReport(Parents parentsObject){
		
		List<Parent> parents = parentsObject.getParent();
		for(Parent parent : parents){
			this.prepareReportFile(parent);	
			this.sendEmails(parent.getParentname(), parent.getParentemail());
		}		
	}
	
	private void sendEmails(String folderName, String email){
		File folder = new File("E:\\ab\\"+folderName);
		File[] listOfFiles = folder.listFiles();
		for (int i = 0; i < listOfFiles.length; i++) {
		      if (listOfFiles[i].isFile()) {
		    	  logger.info("File " + listOfFiles[i].getName()); 
		    	  sendMail.sendMailWithAttachment(email, listOfFiles[i].getAbsolutePath(),folderName,listOfFiles[i].getName());
		    	  
		      } else if (listOfFiles[i].isDirectory()) {
		    	  logger.info("Directory " + listOfFiles[i].getName());
		      }
		    }
		//sendMail.sendMailWithAttachment();
	}
	
	private boolean createParentFolder(String fileName){
		File dir = new File(fileName);
		boolean result = false;
		if (!dir.exists()) {		   
		   result = dir.mkdir();  		     
		 }
		return result;
	}
	
	private void prepareReportFile(Parent parent){
		
		boolean result = this.createParentFolder("E:\\ab\\"+parent.getParentname());
		logger.info("Parent Folder created "+result);
		
		List<Student> students = parent.getStudents();
		for(Student student: students){
			List<Course> courses = student.getCourses();
			ExcelData.writeDataToExcel(student.getId(), student.getName(), courses, "E:\\ab\\"+parent.getParentname());
			
		}
		
		
	}
	

}
